package cn.com.shadowless.xinning.view.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.arialyy.annotations.Download;
import com.arialyy.aria.core.Aria;
import com.arialyy.aria.core.task.DownloadTask;
import com.bumptech.glide.Glide;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.impl.LoadingPopupView;
import com.lxj.xpopup.util.SmartGlideImageLoader;
import com.mengpeng.mphelper.ToastUtils;
import com.tencent.smtt.export.external.TbsCoreSettings;
import com.tencent.smtt.sdk.QbSdk;
import com.tencent.smtt.sdk.TbsDownloader;
import com.tencent.smtt.sdk.TbsListener;
import com.tencent.smtt.sdk.TbsReaderView;

import java.io.EOFException;
import java.io.File;
import java.net.ConnectException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;
import cn.com.shadowless.xinning.MyApplication;
import cn.com.shadowless.xinning.R;
import cn.com.shadowless.xinning.utils.Constants;
import cn.com.shadowless.xinning.utils.PreferencesUtils;
import cn.com.shadowless.xinning.utils.ProgressDialogUtils;
import cn.com.shadowless.xinning.view.BaseActivity;

/**
 * The type Office activity.
 *
 * @author sHadowLess
 */
public class OfficeActivity extends BaseActivity implements TbsListener, QbSdk.PreInitCallback {

    private final String TAG = OfficeActivity.class.getSimpleName();

    /**
     * The Office main.
     */
    @BindView(R.id.office_main)
    FrameLayout officeMain;
    /**
     * The Office tab back btn.
     */
    @BindView(R.id.office_tab_back_btn)
    ImageView officeTabBackBtn;

    private TbsReaderView tbsReaderView = null;
    private String suffix = null;
    private LoadingPopupView loadingPopupView = null;
    private LoadingPopupView downLoadingPopupView = null;

    @Override
    protected int setLayout() {
        return R.layout.activity_office;
    }

    @Override
    protected void setData() {
        Aria.download(this).register();
        loadingPopupView = new XPopup
                .Builder(this)
                .dismissOnTouchOutside(false)
                .asLoading("正在下载文档浏览组件");
        downLoadingPopupView = new XPopup
                .Builder(this)
                .dismissOnTouchOutside(false)
                .asLoading("正在下载文档");
        tbsReaderView = new TbsReaderView(this, (integer, o, o1) -> {

        });
        officeMain.addView(tbsReaderView, new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        initTbs();
    }

    @Override
    protected void onDestroy() {
        ProgressDialogUtils.dismissProgressDialog();
        if (tbsReaderView != null) {
            tbsReaderView.onStop();
        }
        if (TbsDownloader.isDownloading()) {
            TbsDownloader.stopDownload();
        }
        Aria.download(this).unRegister();
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        finish();
    }

    /**
     * Start.
     *
     * @param task the task
     */
    @Download.onTaskStart
    protected void start(DownloadTask task) {
        downLoadingPopupView.show();
    }

    /**
     * Complete.
     *
     * @param task the task
     */
    @Download.onTaskComplete
    protected void complete(DownloadTask task) {
        downLoadingPopupView.dismiss();
        openFile(task.getFilePath());
    }

    /**
     * Fail.
     *
     * @param task the task
     * @param e    the e
     */
    @Download.onTaskFail
    protected void fail(DownloadTask task, Exception e) {
        downLoadingPopupView.dismiss();
        ToastUtils.onErrorShowToast(exceptionMessage(checkException(e)));
    }

    /**
     * On view clicked.
     */
    @OnClick(R.id.office_tab_back_btn)
    public void onViewClicked() {
        finish();
    }

    private void openFile(String path) {
        Bundle bundle = new Bundle();
        //文件路径
        bundle.putString("filePath", path);
        //临时文件的路径，必须设置，否则会报错
        bundle.putString("tempPath", Constants.DOWNLOAD_FILE_PATH + "temp");
        //准备
        boolean result = tbsReaderView.preOpen(suffix, false);
        if (result) {
            //预览文件
            tbsReaderView.openFile(bundle);
        } else {
            ToastUtils.onErrorShowToast("该文件类型不支持查看");
        }
    }

    private void openFile() {
        Intent intent = getIntent();
        String fileName = intent.getStringExtra("fileName");
        suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        String fileUrl = Constants.FILE_URL + intent.getStringExtra("fileUrl");
        if (isPic(suffix)) {
            ImageView imageView = new ImageView(this);
            officeMain.addView(imageView, new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            imageView.setOnClickListener(v -> new XPopup
                    .Builder(OfficeActivity.this)
                    .asImageViewer(imageView, fileUrl, new SmartGlideImageLoader())
                    .show());
            Glide.with(this).load(fileUrl).into(imageView);
        } else {
            File file = new File(Constants.DOWNLOAD_FILE_PATH + fileName);
            if (file.exists()) {
                openFile(Constants.DOWNLOAD_FILE_PATH + fileName);
            } else {
                Aria.download(this).load(fileUrl).setFilePath(Constants.DOWNLOAD_FILE_PATH + fileName).create();
            }
        }
    }

    private boolean isPic(String suffix) {
        if (suffix.equals("jpg")) {
            return true;
        } else if (suffix.equals("jpeg")) {
            return true;
        } else if (suffix.equals("png")) {
            return true;
        } else {
            return false;
        }
    }

    private void initTbs() {
        QbSdk.setDownloadWithoutWifi(true);
        HashMap<String, Object> map = new HashMap<>();
        map.put(TbsCoreSettings.TBS_SETTINGS_USE_SPEEDY_CLASSLOADER, true);
        map.put(TbsCoreSettings.TBS_SETTINGS_USE_DEXLOADER_SERVICE, true);
        QbSdk.initTbsSettings(map);
        QbSdk.setTbsListener(this);

        boolean needDownload = TbsDownloader.needDownload(MyApplication.getInstance(), TbsDownloader.DOWNLOAD_OVERSEA_TBS);
        Log.e(TAG, "initTbs: " + needDownload);
        if (needDownload) {
            loadingPopupView.show();
            TbsDownloader.startDownload(MyApplication.getInstance());
        } else {
            if (QbSdk.isTbsCoreInited()) {
                openFile();
            } else {
                int progress = PreferencesUtils.getInt(MyApplication.getInstance(), "progress", 0);
                if (progress == 0) {
                    loadingPopupView.show();
                    TbsDownloader.startDownload(MyApplication.getInstance());
                } else {
                    QbSdk.initX5Environment(MyApplication.getInstance(), this);
                }
            }
        }
    }

    /**
     * Check exception constants . error.
     *
     * @param e the e
     * @return the constants . error
     */
    public Constants.ERROR checkException(Throwable e) {
        if (e instanceof SocketTimeoutException) {
            return Constants.ERROR.TIMEOUT;
        } else if (e instanceof ConnectException) {
            return Constants.ERROR.CONNECT_REFUSED;
        } else if (e instanceof SocketException) {
            return Constants.ERROR.SOCKET_CLOSED;
        } else if (e instanceof EOFException) {
            return Constants.ERROR.WAVE;
        } else if (e instanceof UnknownHostException) {
            return Constants.ERROR.UN_KNOW_HOST;
        } else {
            return Constants.ERROR.DEFAULT;
        }
    }

    /**
     * Exception message string.
     *
     * @param error the error
     * @return the string
     */
    public String exceptionMessage(Constants.ERROR error) {
        switch (error) {
            case UN_KNOW_HOST:
                return Constants.ERROR_UN_KNOW_HOST_MESSAGE;
            case TIMEOUT:
                return Constants.ERROR_TIME_OUT_MESSAGE;
            case SOCKET_CLOSED:
                return Constants.ERROR_SOCKET_CLOSED_MESSAGE;
            case CONNECT_REFUSED:
                return Constants.ERROR_CONNECT_REFUSED_MESSAGE;
            case WAVE:
                return Constants.ERROR_WAVE_MESSAGE;
            default:
                return Constants.ERROR_DEFAULT;
        }
    }

    @Override
    public void onDownloadFinish(int i) {
        Log.e(TAG, "onDownloadFinish: " + i);
    }

    @Override
    public void onInstallFinish(int i) {
        Log.e(TAG, "onInstallFinish: 内核下载成功");
        PreferencesUtils.putInt(MyApplication.getInstance(), "progress", i);
        QbSdk.initX5Environment(MyApplication.getInstance(), this);
    }

    @Override
    public void onDownloadProgress(int i) {
        Log.e(TAG, "onDownloadProgress: " + i);
        PreferencesUtils.putInt(MyApplication.getInstance(), "progress", i);
    }

    @Override
    public void onCoreInitFinished() {
        Log.e(TAG, "onCoreInitFinished: 初始化完成");
    }

    @Override
    public void onViewInitFinished(boolean b) {
        Log.e(TAG, "onViewInitFinished: 是否使用x5内核" + b);
        if (!b) {
            loadingPopupView.show();
            TbsDownloader.startDownload(MyApplication.getInstance());
        } else {
            loadingPopupView.dismiss();
            openFile();
        }
    }
}